<template>
  <div>
    <!-- 搜索区域 -->
    <div style="margin-bottom: 20px">
      <el-input v-model="data.name" placeholder="请输入社团名称" style="width: 200px" clearable></el-input>
      <el-button type="primary" style="margin-left: 10px" @click="load">查询</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="handleAdd">新增</el-button>
      <el-button type="danger" style="margin-left: 10px" :disabled="!data.ids.length" @click="delBatch">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="社团名称" />
      <el-table-column prop="descr" label="社团介绍" show-overflow-tooltip />
      <el-table-column prop="presidentId" label="社长ID" />
      <el-table-column label="操作" width="380">
        <template #default="scope">
          <el-button type="primary" @click="handleView(scope.row)">查看</el-button>
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="primary" @click="handleApplications(scope.row)">查看申请</el-button>
          <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div style="margin-top: 20px">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 申请审批对话框 -->
    <el-dialog v-model="data.applicationsVisible" title="社团申请审批" width="800px">
      <el-table :data="data.applications" stripe>
        <el-table-column prop="studentName" label="申请人" />
        <el-table-column prop="applyTime" label="申请时间" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button 
              v-if="scope.row.status === '待审核'"
              type="success" 
              size="small" 
              @click="handleApprove(scope.row)"
            >通过</el-button>
            <el-button 
              v-if="scope.row.status === '待审核'"
              type="danger" 
              size="small" 
              @click="handleReject(scope.row)"
            >拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 表单对话框 -->
    <el-dialog v-model="data.formVisible" :title="data.form.id ? '编辑' : '新增'" width="500px">
      <el-form :model="data.form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="社团名称" prop="name">
          <el-input v-model="data.form.name" placeholder="请输入社团名称"></el-input>
        </el-form-item>
        <el-form-item label="社团介绍" prop="descr">
          <el-input v-model="data.form.descr" type="textarea" placeholder="请输入社团介绍"></el-input>
        </el-form-item>
        <el-form-item label="社长ID" prop="presidentId">
          <el-input v-model="data.form.presidentId" placeholder="请输入社长ID"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import { useRouter } from 'vue-router'

const router = useRouter()
const formRef = ref()
// 从 localStorage 获取当前用户信息
const user = JSON.parse(localStorage.getItem('xm-pro-user'))

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  applicationsVisible: false,
  form: {},
  applications: [],
  ids: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入社团名称', trigger: 'blur' }
  ],
  presidentId: [
    { required: true, message: '请输入社长ID', trigger: 'blur' }
  ]
}

// 加载数据
const load = () => {
  request.get(`/club/selectByPresidentId/${user.id}`).then(res => {
    if (res.code === '200') {
      data.tableData = res.data || []
      data.total = res.data ? res.data.length : 0
    } else {
      ElMessage.error(res.msg || '加载数据失败')
    }
  }).catch(err => {
    console.error('加载数据失败:', err)
    ElMessage.error('加载数据失败')
  })
}

// 新增
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}

// 编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}

// 保存
const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (data.form.id) {
        update()
      } else {
        add()
      }
    }
  })
}

// 新增请求
const add = () => {
  request.post('/club/add', data.form).then(res => {
    if (res.code === '200') {
      data.formVisible = false
      ElMessage.success('新增成功')
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 更新请求
const update = () => {
  request.put('/club/updateById', data.form).then(res => {
    if (res.code === '200') {
      data.formVisible = false
      ElMessage.success('更新成功')
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

// 删除
const del = (id) => {
  ElMessageBox.confirm('确认删除该社团吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete('/club/deleteById/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 批量删除
const delBatch = () => {
  ElMessageBox.confirm('确认删除选中的社团吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.post('/club/deleteBatch', data.ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

// 表格多选
const handleSelectionChange = (rows) => {
  data.ids = rows.map(row => row.id)
}

// 分页大小改变
const handleSizeChange = (val) => {
  data.pageSize = val
  load()
}

// 页码改变
const handleCurrentChange = (val) => {
  data.pageNum = val
  load()
}

// 查看社团详情
const handleView = (row) => {
  router.push({
    path: '/president/clubs-all',
    query: { clubId: row.id }
  })
}

// 获取申请状态对应的标签类型
const getStatusType = (status) => {
  const types = {
    '待审核': 'warning',
    '已通过': 'success',
    '已拒绝': 'danger'
  }
  return types[status] || 'info'
}

// 查看申请列表
const handleApplications = async (row) => {
  try {
    const res = await request.get('/club/application/list', {
      params: { 
        clubId: row.id,
        pageNum: 1,
        pageSize: 10
      }
    })
    if (res.code === '200') {
      data.applications = res.data.list
      data.applicationsVisible = true
    } else {
      ElMessage.error(res.msg || '获取申请列表失败')
    }
  } catch (err) {
    console.error('获取申请列表失败:', err)
    ElMessage.error('获取申请列表失败')
  }
}

// 通过申请
const handleApprove = async (row) => {
  try {
    await ElMessageBox.confirm('确定通过该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    })
    
    const res = await request.post('/club/application/approve', {
      id: row.id
    })
    
    if (res.code === '200') {
      ElMessage.success('已通过申请')
      handleApplications({ id: row.clubId }) // 刷新申请列表
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 拒绝申请
const handleReject = async (row) => {
  try {
    await ElMessageBox.confirm('确定拒绝该申请吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await request.post('/club/application/reject', {
      id: row.id
    })
    
    if (res.code === '200') {
      ElMessage.success('已拒绝申请')
      handleApplications({ id: row.clubId }) // 刷新申请列表
    } else {
      ElMessage.error(res.msg || '操作失败')
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  load()
})
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 